package com.shanshi.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LocationActivity extends MainActivity  implements LocationSource,AMapLocationListener,AMap.OnMarkerClickListener {
	
	//private String[] items = {"百度地图", "高德地图"};
	private AMap aMap;
	private UiSettings mUiSettings;
	//定位需要的声明
	private AMapLocationClient mLocationClient = null;//定位发起端
	private AMapLocationClientOption mLocationOption = null;//定位参数
	private OnLocationChangedListener mListener = null;//定位监听器
	//标识，用于判断是否只显示一次定位信息和用户重新定位
	private boolean isFirstLoc = true;
	private MapView mMapView = null;
	private TextView tv_title;
	private TextView tv_info;
	private String mylatLng,endlatLang;
	private LatLng localposition;
	private String mode;
	private TextView title;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.location);
		initGPS();
		tv_title = (TextView) findViewById(R.id.tv_location_title);
		tv_info = (TextView) findViewById(R.id.tv_location_info);
		title = (TextView) findViewById(R.id.title);
		//获取地图控件引用
		mMapView = (MapView) findViewById(R.id.mapTest);
		//在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
		mMapView.onCreate(savedInstanceState);
		if (aMap == null) {
			aMap = mMapView.getMap();
			//设置显示定位按钮 并且可以点击
			UiSettings settings = aMap.getUiSettings();
			//设置定位监听
			aMap.setLocationSource(this);
			// 是否显示定位按钮
			settings.setMyLocationButtonEnabled(true);
			// 是否可触发定位并显示定位层
			aMap.setMyLocationEnabled(true);
			aMap.setOnMarkerClickListener(this);
			aMap.getUiSettings().setZoomControlsEnabled(false);

		}
		initLoc();
	}
	//定位
	private void initLoc() {
		//初始化定位
		mLocationClient = new AMapLocationClient(getApplicationContext());
		//设置定位回调监听
		mLocationClient.setLocationListener(this);
		//初始化定位参数
		mLocationOption = new AMapLocationClientOption();
		//设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
		mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
		//设置是否返回地址信息（默认返回地址信息）
		mLocationOption.setNeedAddress(true);
		//设置是否只定位一次,默认为false
		mLocationOption.setOnceLocation(true);
		//设置是否强制刷新WIFI，默认为强制刷新
		mLocationOption.setWifiActiveScan(true);
		//设置是否允许模拟位置,默认为false，不允许模拟位置
		mLocationOption.setMockEnable(false);
		//设置定位间隔,单位毫秒,默认为2000ms
		mLocationOption.setInterval(2000);
		//给定位客户端对象设置定位参数
		mLocationClient.setLocationOption(mLocationOption);
		//启 动定位
		mLocationClient.startLocation();
	}
	@Override
	public void activate(OnLocationChangedListener listener) {
		mListener = listener;
	}

	@Override
	public void deactivate() {
		mListener = null;
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// Log.e("location", "onLocationChanged: "+amapLocation.getDistrict() );
		settitle(amapLocation.getCity());

		tv_title.setText(amapLocation.getCity()+amapLocation.getDistrict());
		tv_info.setText(amapLocation.getCity()+amapLocation.getDistrict()+amapLocation.getStreet()+amapLocation.getStreetNum());
		if (amapLocation != null) {
			if (amapLocation.getErrorCode() == 0) {
				//定位成功回调信息，设置相关消息
				amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见官方定位类型表
				amapLocation.getLatitude();//获取纬度
				amapLocation.getLongitude();//获取经度
				amapLocation.getAccuracy();//获取精度信息
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				Date date = new Date(amapLocation.getTime());
				df.format(date);//定位时间
				amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
				amapLocation.getCountry();//国家信息
				amapLocation.getProvince();//省信息
				amapLocation.getCity();//城市信息
				amapLocation.getDistrict();//城区信息
				amapLocation.getStreet();//街道信息
				amapLocation.getStreetNum();//街道门牌号信息
				amapLocation.getCityCode();//城市编码
				amapLocation.getAdCode();//地区编码
				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				// 如果不设置标志位，此时再拖动地图时，它会不断将地图移动到当前的位置
				if (isFirstLoc) {
					//设置缩放级别
					aMap.moveCamera(CameraUpdateFactory.zoomTo(17));
					//将地图移动到定位点
					mylatLng = amapLocation.getLongitude()+""+","+ amapLocation.getLatitude();
					localposition=new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
					aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude())));
					//点击定位按钮 能够将地图的中心移动到定位点
					mListener.onLocationChanged(amapLocation);
					//添加图钉
					aMap.addMarker(getMarkerOptions(amapLocation,new LatLng(30.679284,103.998208)));
					//aMap.addMarker(getMarkerOptions(amapLocation,new LatLng(103.997274,30.677531)));
					//aMap.addMarker(getMarkerOptions());
					//获取定位信息
					StringBuffer buffer = new StringBuffer();
					buffer.append(amapLocation.getCountry() + "" + amapLocation.getProvince() + "" + amapLocation.getCity() + "" + amapLocation.getProvince() + "" + amapLocation.getDistrict() + "" + amapLocation.getStreet() + "" + amapLocation.getStreetNum());
					//Toast.makeText(getApplicationContext(), buffer.toString(), Toast.LENGTH_LONG).show();
					isFirstLoc = false;
				}


			} else {
				//显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
				Log.e("AmapError", "location Error, ErrCode:"
						+ amapLocation.getErrorCode() + ", errInfo:"
						+ amapLocation.getErrorInfo());

				Toast.makeText(getApplicationContext(), "定位失败", Toast.LENGTH_LONG).show();
			}
		}
	}

	private void settitle(String name) {
		title.setText(name);
	}

	//自定义一个图钉，并且设置图标，当我们点击图钉时，显示设置的信息
	private MarkerOptions getMarkerOptions(AMapLocation amapLocation,LatLng latLng) {
		//设置图钉选项
		MarkerOptions options = new MarkerOptions();
		//图标
		options.icon(BitmapDescriptorFactory.fromResource(R.drawable.map));
		//位置
		options.position(latLng);
		StringBuffer buffer = new StringBuffer();
		buffer.append(amapLocation.getCountry() + "" + amapLocation.getProvince() + "" + amapLocation.getCity() +  "" + amapLocation.getDistrict() + "" + amapLocation.getStreet() + "" + amapLocation.getStreetNum());
		tv_title.setText(amapLocation.getProvider()+amapLocation.getCity()+amapLocation.getDistrict());
//		//标题
		options.title(buffer.toString());
//		//子标题
		options.snippet("我在");
//		//设置多少帧刷新一次图片资源
		options.period(60);

		return options;

	}



	public void nextPage(View view){
		switch (view.getId()) {
			case R.id.fanhui:
				finish();
				break;


		}
	}

	@Override
	public boolean onMarkerClick(Marker marker) {
		tv_title.setText(marker.getTitle());
		tv_info.setText(marker.getSnippet());
		endlatLang=marker.getPosition()+"";
		Log.e("local",mylatLng+"目的地"+endlatLang);
		return true;
	}
	//精确定位点击事件 镜头以自己定位为中心 开始定位
	public void locatio(View view) {
		aMap.moveCamera(CameraUpdateFactory.changeLatLng(localposition));
		mLocationClient.startLocation();
	}
	//lead导航点击事件
	public void lead(View view1) {
		mode = "walk";
		Intent intent = new Intent();
		intent.putExtra("start", mylatLng);
		intent.putExtra("end", "103.998208,30.679284");
		intent.putExtra("mode", "walk");
		intent.setClass(LocationActivity.this, GaoDeActivity.class);

		startActivity(intent);
	}
	//检测gps开启
	private void initGPS() {
		LocationManager locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		// 判断GPS模块是否开启，如果没有则开启
		if (!locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			Toast.makeText(LocationActivity.this, "请打开GPS",
					Toast.LENGTH_SHORT).show();
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setMessage("请打开GPS");
			dialog.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {

							// 转到手机设置界面，用户设置GPS
							Intent intent = new Intent(
									Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

						}
					});
			dialog.setNeutralButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					arg0.dismiss();
				}
			} );
			dialog.show();
		} else {
			// 弹出Toast
//          Toast.makeText(TrainDetailsActivity.this, "GPS is ready",
//                  Toast.LENGTH_LONG).show();
//          // 弹出对话框
//          new AlertDialog.Builder(this).setMessage("GPS is ready")
//                  .setPositiveButton("OK", null).show();
		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
		//在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
		mMapView.onDestroy();
	}
	@Override
	protected void onResume() {
		super.onResume();
		//在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
		mMapView.onResume();
	}
	@Override
	protected void onPause() {
		super.onPause();
		//在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
		mMapView.onPause();
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
		mMapView.onSaveInstanceState(outState);
	}




}
